/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.util;

import com.koron.web.servlet.CASLoginAction;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.UUID;


/**
 * @author liaodf
 * @desc 图片验证码
 * @date 2022年6月28日
 */
@RestController
@RequestMapping("/verifyCode")
public class CodeAction {
    public final static String VERIFY_CODE = "verify_code";

    @RequestMapping("/getCode.htm")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg");
        //禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //创建验证码生成器实例取得生成图片和随机字符串
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();
        String text = vc.getText();
        // 生成随机码
        String uuid = UUID.randomUUID().toString().replace("_", "");
        // 随机码存到session
        request.getSession().setAttribute(VERIFY_CODE, uuid);
        VerifyCodeBean bean = new VerifyCodeBean();
        bean.setCode(text);
        bean.setDate(System.currentTimeMillis() + 180000L);
        CASLoginAction.VerifyCode.put(uuid, bean);
        //用流传输
        ServletOutputStream outputStream = response.getOutputStream();
        VerifyCode.output(image, outputStream);
    }
}

